package com.example.tvhttp;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/*
 * Main Activity class that loads {@link MainFragment}.
 */
public class MainActivity extends FragmentActivity {

    private static String url = "http://v.juhe.cn/toutiao/index?key=81b9df386983702626a3bcdd04f2ca0e&type=yule";

    //适配器
    private NewsListAdapter mListAdapter;

    //列表控件
    private RecyclerView mRecyclerView;

    //异步(**选取Android OS的handler**)
    private Handler mHandler = new Handler(Looper.myLooper()){

        @Override
        public void handleMessage(@NonNull Message msg) {
            if(msg.what == 100){
                String data = (String) msg.obj;

                //将json数据转为数据实体类(JAVA 对象)
                NewsInfo newsInfo = new Gson().fromJson(data, NewsInfo.class);
                if(null != mListAdapter){

                    //实例化NewsInfo；调用getResult()方法，返回result，result类型为ResultDTO；类ResultDTO里调用getData()方法，返回data（*所有新闻信息*）,data类型：List<DataDTO>
                    mListAdapter.setListData(newsInfo.getResult().getData());
                }

            }
        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化适配器

        //MainActivity.this代表当前MainActivity实例
        // （Activity是Context的子类，所以可以将MainActivity的实例作为Context传递给NewsListAdapter的构造函数。这样，在NewsListAdapter内部就可以使用这个上下文来访问资源、启动活动等操作。）
        mListAdapter = new NewsListAdapter(MainActivity.this);

        //初始化列表控件
        mRecyclerView = findViewById(R.id.recyclerview);

        //设置适配器
        mRecyclerView.setAdapter(mListAdapter);

        // 发送HTTP GET请求
        getHttpData();

    }


    private void getHttpData() {


        //创建OkHttpClient对象
        OkHttpClient client = new OkHttpClient();
        //构建Request对象
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        //通过OkHttpClient对象和Request对象来构建Call对象

        Call call = client.newCall(request);
        //通过Call对象的enqueue（Callback）方法来执行异步请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d("--------","onFailure:"+e.toString());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                Log.d("--------","onResponse:"+response.body().string());

                String data = response.body().string();

                //不能直接在这里操作UI，因为这是一个耗时操作，要使用handler
                Message message = new Message();
                message.what = 100;
                message.obj = data;

                //发送
                mHandler.sendMessage(message);

            }
        });


    }
}